package com.xzc._3_running;

import bitronix.tm.TransactionManagerServices;
import com.xzc._1_build.Base_Test;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;

/**
 * 事务与持久化
 * 事务是JTA，XA事务
 * 4.2.4.9 还有一些持久化及事务的配置，感觉很少用，就先不用了。
 */
public class Transaction {
    Base_Test t = new Base_Test();
    KieBase kBase1;
    KieSession kSession;

    public void init() {
        t.createContainerByClasspath();
        KieBase kBase1 = t.getKieContainer().getKieBase("KBase1");
        KieSession kSession = t.getKieContainer().newKieSession("KSession2_1");
    }

    /**
     * 使用JBOSS默认的事务管理器,XA
     *
     * @throws Exception
     */
    public void useJBOSSTrazc() throws Exception {
        KieServices kieServices = KieServices.Factory.get();
        Environment env = kieServices.newEnvironment();
        env.set(EnvironmentName.ENTITY_MANAGER_FACTORY,
                Persistence.createEntityManagerFactory("emf-name"));
        env.set(EnvironmentName.TRANSACTION_MANAGER,
                TransactionManagerServices.getTransactionManager());

// KieSessionConfiguration may be null, and a default will be used
        KieSession ksession =
                kieServices.getStoreServices().newKieSession(kBase1, null, env);
        int sessionId = ksession.getId();

        UserTransaction ut =
                (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
        ut.begin();
        ksession.insert(new String("data1"));
        ksession.insert(new String("data2"));
        ksession.startProcess("process1");
        ut.commit();
    }
}
